package com.tinywind.boot.module.common.controller;

import com.tinywind.boot.common.base.BaseResult;
import com.tinywind.boot.common.consts.SystemConst;
import com.tinywind.boot.common.utils.RedisUtil;
import com.tinywind.boot.common.utils.idgen.IdGenerate;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liuxingyu01
 * @date 2021-12-29-16:20
 * @description 验证码操作处理
 * @documentation https://github.com/whvcse/easycaptcha
 **/
@RestController
@RequestMapping("/system")
public class CaptchaController {

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 生成验证码
     */
    @GetMapping("/getCaptcha")
    public BaseResult getCode(@RequestParam(required = false, defaultValue = "", value = "type") String captchaType) {
        Map<String,String> result = new HashMap<>();

        // 保存验证码信息
        String uuid = IdGenerate.uuid();
        String verifyKey = SystemConst.CAPTCHA_CODE_KEY + ":" + uuid;

        // 生成验证码
        if ("math".equals(captchaType)) {
            ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
            captcha.setLen(3);  // 几位数运算，默认是两位
            String code = captcha.text().toLowerCase();

            redisUtil.set(verifyKey, code, 60);

            result.put("uuid", uuid);
            result.put("img", captcha.toBase64().split(",")[1]);
            return BaseResult.success(result);
        } else if ("char".equals(captchaType)) {
            // 设置类型，纯数字、纯字母、字母数字混合
            // gif类型的验证码
            GifCaptcha captcha = new GifCaptcha(130, 48, 6);
            captcha.setCharType(Captcha.TYPE_DEFAULT);
            String code = captcha.text().toLowerCase();

            redisUtil.set(verifyKey, code, 60);

            result.put("uuid", uuid);
            result.put("img", captcha.toBase64().split(",")[1]);
            return BaseResult.success(result);
        } else {
            return BaseResult.failure("请传入参数：验证码类型！");
        }
    }

}
